<template>
	<view>
		<div style="height: 44px;background-color: #fff;width:100%"></div>
		<view class="u-page__item">
			<up-navbar :safeAreaInsetTop="false" title="业绩分配" :fixed="false"
				@leftClick="leftClickHandle" :title-style="{'font-size':'20px'}">
				<template #right>
					<view class="u-nav-slot">
						<image src="/static/images/iconPark-more-two Ti115ro@2x.png" alt=""
							style="width:44rpx;height:44rpx;" v-show="!isDelete"
							@tap="isDelete = true; emitter.emit('openDelete')"></image>
					</view>
				</template>
			</up-navbar>
		</view>
		<up-tabs :list="list1" @click="tapChange" style="background: #fff;" itemStyle='width:50%;padding:20rpx'
			lineWidth="180rpx"></up-tabs>
		<div class="search_box" style="margin-top:-4px;">
			<up-search placeholder="搜索客户姓名/手机号" v-model="searchValue" shape="share" :showAction="false"
				@change="searchChange" class="seach_input"></up-search>
			<div class="search_r" @tap="openPopup">
				<image src="/static/images/search.png" alt="" style="width: 18px;
height: 18px;"></image>
				<div class="text-r">筛选</div>



			</div>
		</div>

		<AssignmentModal></AssignmentModal>
		<ScreenPopup></ScreenPopup>

		<scroll-view :scroll-top="0" scroll-y="true" class="scroll-Y" :style="{'height': isDelete ? 'calc(100vh - 545rpx)':'calc(100vh - 430rpx)'}">
			<Unallocated :unallocatedList="unallocatedList" v-if="isUnallocatedShow"></Unallocated>
			<Allocated :allocatedList="allocatedList" v-if="!isUnallocatedShow"> </Allocated>


			<!-- 未分配订单分页 - 固定在底部 -->
		


		</scroll-view>
			<div v-if="unallocatedList.length > 0">
				<u-pagination v-show="isUnallocatedShow" :current-page="UnallocatedPageNumber + 1" :page-size="10"
					:total="unallocatedTotal" @current-change="handleUnallocatedPageChange" style="margin: 20rpx 30rpx 0;" />
			</div>
			<!-- 已分配订单分页 - 固定在底部 -->
			<div v-if="allocatedList.length > 0">
				<u-pagination v-show="!isUnallocatedShow && isShowPage2" :current-page="AllocatedPageNumber + 1"
					:page-size="10" :total="allocatedTotal" @current-change="handleAllocatedPageChange"
					style="margin: 20rpx 30rpx 0;"  />
			</div>
		<up-modal :show="DelShow" @confirm='confirmDel' @cancel="DelShow = false" :closeOnClickOverlay="true"
			@close="DelShow = false" content='确定要删除吗' showCancelButton="true" showConfirmButton="true"></up-modal>
		<div class="del_box" v-show="isDelete">
			<div class="del_left">已选择：{{ selectNumbers }}</div>
			<div> <up-button text="确认删除" style="	width: 147px;
		height: 56px;
		line-height: 22px;
		background: linear-gradient(88.71deg, rgba(222, 134, 143, 1) 15.3%, rgba(189, 49, 36, 1) 74.51%);
		color: rgba(255, 255, 255, 1);
		font-size: 15px;
		text-align: center;
		font-family: -regular;" @tap="DelShow = true; console.log(21321)"></up-button></div>

		</div>
	</view>
</template>

<script setup>
import { reactive, ref, nextTick } from 'vue';
import { getOrderList, getorderAchList, delAchievement } from '../../utils/performance';
import Unallocated from './components/Unallocated.vue'
import Allocated from './components/Allocated.vue';
import AssignmentModal from './components/AssignmentModal.vue'
import ScreenPopup from './components/ScreenPopup.vue';
import emitter from '../../utils/eventBus';
const isDelete = ref(false)
const searchValue = ref('')
const isUnallocatedShow = ref(true)
const UnallocatedPageNumber = ref(0)
const AllocatedPageNumber = ref(0)
const unallocatedTotal = ref(0)
const allocatedTotal = ref(0)
const isShowPage1 = ref(false)
const isShowPage2 = ref(false)
const leftClickHandle = ()=>{
   if(isDelete.value){
	      isDelete.value=false
		   emitter.emit('closeDelete')
   }else {
	    uni.switchTab({ url: '/pages/workbenches/workbenches' })
   }

}
// 创建响应式数据  
const list1 = reactive([
	{ name: '未分配订单', id: 0 },
	{ name: '已分配订单', id: 1 },
]);
const DelShow = ref(false)
// 定义方法  
const IsAchievement = ref('未分配订单')
const tapChange = (v) => {
	console.log(v)
	selectNumbers.value = 0
	delList.value = []
	isDelete.value = false
	currentFilterParams.value = {}
	emitter.emit('cleardata')
	if (searchValue.value != '') {
		searchValue.value = ''
	}
	// 确保切换标签时清空ScreenPopup组件数据
	if (v.name == '已分配订单') {
		IsAchievement.value = '已分配订单'
		isUnallocatedShow.value = false
		isShowPage1.value = false
		// 使用setTimeout确保接口调用在最后执行
		setTimeout(() => {
			getallocatedLists()
		}, 200)
	} else {
		IsAchievement.value = '未分配订单'
		isShowPage1.value = true
		isUnallocatedShow.value = true
		// 使用setTimeout确保接口调用在最后执行
		setTimeout(() => {
			getOrderListHandle()
		}, 200)
	}
}
const unallocatedList = ref([])
const allocatedList = ref([])
const getOrderListHandle = async () => {
	try {
		const res = await getOrderList({
			businessId: uni.getStorageSync('businessId'),
			isAllot: 0,
			pageNumber: UnallocatedPageNumber.value + 1,
			pageSize: 10
		})
		console.log(res)
		unallocatedList.value = res.data.records || [];
		if (unallocatedList.value.length > 0) {
			isShowPage1.value = true
		}

		unallocatedTotal.value = res.data.total || 0;
	} catch (e) {
		console.error('获取未分配订单失败:', e)
	} finally {

	}
}
const allocatedListHandle = async (data) => {
	for (const item of data) {
		try {
			const res1 = await getorderAchList({
				orderId: item.orderId
			})
			item.data = res1.data || {}

		} catch (e) {
			console.error('获取订单业绩失败:', e)
			item.data = {}
		}
	}
	allocatedList.value = data
	if (allocatedList.value.length > 0) { isShowPage2.value = true }
	console.log('处理后的数据:', data)
	uni.hideLoading()
}
const getallocatedLists = async () => {
	uni.showLoading({
		title: '加载中...'
	})
	try {
		const res = await getOrderList({
			businessId: uni.getStorageSync('businessId'),
			isAllot: 1,
			pageNumber: AllocatedPageNumber.value + 1,
			pageSize: 10
		})
		console.log(res)
		//allocatedList.value = res.data.records || [];
		allocatedTotal.value = res.data.total || 0;
		await allocatedListHandle(res.data.records)
	} catch (e) {
		console.error('获取已分配订单失败:', e)
	}
}
// 添加分页处理函数
const handleUnallocatedPageChange = (currentPage) => {
	UnallocatedPageNumber.value = currentPage - 1;
	// 滚动到顶部
	// uni.pageScrollTo({
	// 	scrollTop: 0,
	// 	duration: 300
	// });
	getOrderListHandle();
}

const handleAllocatedPageChange = (currentPage) => {
	AllocatedPageNumber.value = currentPage - 1;
	// 滚动到顶部
	// uni.pageScrollTo({
	// 	scrollTop: 0,
	// 	duration: 300
	// });
	getallocatedLists();
}

const searchNameHandle = async (e) => {
	if (IsAchievement.value == '未分配订单') {
		try {
			const res = await getOrderList({
				businessId: uni.getStorageSync('businessId'),
				isAllot: 0,
				pageNumber: UnallocatedPageNumber.value + 1,
				pageSize: 10,
				name: e
			})
			console.log(res)
			unallocatedList.value = res.data.records || [];
			unallocatedTotal.value = res.data.total || 0;
		} catch (e) {
			console.error('获取未分配订单失败:', e)
		}
	} else {
		try {
			const res = await getOrderList({
				businessId: uni.getStorageSync('businessId'),
				isAllot: 1,
				pageNumber: AllocatedPageNumber.value + 1,
				pageSize: 10,
				name: e
			})
			console.log(res)
			//allocatedList.value = res.data.records || [];
			allocatedTotal.value = res.data.total || 0;
			await allocatedListHandle(res.data.records)
		} catch (e) {
			console.error('获取已分配订单失败:', e)
		}

	}

}
const searchPhoneHandle = async (e) => {
	if (IsAchievement.value == '未分配订单') {
		try {
			const res = await getOrderList({
				businessId: uni.getStorageSync('businessId'),
				isAllot: 0,
				pageNumber: UnallocatedPageNumber.value + 1,
				pageSize: 10,
				phoneFirst: e
			})
			console.log(res)
			unallocatedList.value = res.data.records || [];
			unallocatedTotal.value = res.data.total || 0;
		} catch (err) {
			console.error('获取未分配订单失败:', err)
		}
	} else {
		try {
			const res = await getOrderList({
				businessId: uni.getStorageSync('businessId'),
				isAllot: 1,
				pageNumber: AllocatedPageNumber.value + 1,
				pageSize: 10,
				phoneFirst: e
			})
			console.log(res)
			//allocatedList.value = res.data.records || [];
			allocatedTotal.value = res.data.total || 0;
			await allocatedListHandle(res.data.records)
		} catch (e) {
			console.error('获取已分配订单失败:', e)
		}

	}

}
const SearchAllList = () => {

	if (IsAchievement.value == '未分配订单') {
		console.log(12312)
		getOrderListHandle()
	} else {
		getallocatedLists()
	}
}
// 初始加载数据
//getallocatedLists()
// 改为在切换标签时加载数据
emitter.on('reloadData', () => {
	getOrderListHandle()
	getallocatedLists()
})
const selectNumbers = ref('0')
const delList = ref([])
emitter.on('checkboxChange', (val) => {
	console.log(val)
	selectNumbers.value = val.length
	delList.value = val
})
const confirmDel = async () => {
	console.log(delList.value, IsAchievement.value)
	searchValue.value = ''
	emitter.emit('closeDelete')
	if (delList.value.length == 0) {
		DelShow.value = false
		isDelete.value = false
		uni.showToast({
			title: '未删除订单',
			icon: 'none'
		})
		return
	}

	try {
		console.log(delList.value)
		const res = await delAchievement(delList.value)
		if (res.code == 200) {
			uni.showToast({
				title: '删除成功',
				icon: 'success'
			})
			DelShow.value = false
			isDelete.value = false
			if (IsAchievement.value == '未分配订单') {

				getOrderListHandle()
			} else {
				getallocatedLists()
			}
			emitter.emit('clearCheck')

		}

	} catch (E) {
		console.log(E)
	}

}
// 防抖函数实现
const debounce = (fn, delay = 500) => {
	let timer = null;
	return function (...args) {
		if (timer) clearTimeout(timer);
		timer = setTimeout(() => {
			fn.apply(this, args);
		}, delay);
	}
};

// 添加筛选条件状态变量
const currentFilterParams = ref({});

// 原始搜索逻辑函数
const searchChangeLogic = (inputValue) => {
	searchValue.value = inputValue;
	// 构建搜索参数对象
	const searchParams = { ...currentFilterParams.value };

	if (inputValue.trim() === '') {
		// 清空搜索参数但保留筛选条件
		delete searchParams.name;
		delete searchParams.phoneFirst;
		delete searchParams.addPeople;
	} else {
		// 判断输入类型是手机号还是姓名
		const phoneRegex = /^1[3-9]\d{9}$/;
		if (phoneRegex.test(inputValue)) {
			searchParams.phoneFirst = inputValue;
		} else {
			// 检查是否正在使用成交员工筛选
			if (currentFilterParams.value.addPeople) {
				searchParams.addPeople = inputValue;
				delete searchParams.name;
			} else {
				searchParams.name = inputValue;
			}
		}
	}

	// 更新当前筛选条件并触发查询
	currentFilterParams.value = searchParams;
	console.log(searchParams, '条件')
	emitter.emit('UpdateData', searchParams);
};

// 应用防抖到搜索逻辑
const searchChange = debounce(searchChangeLogic, 100);
const openPopup = () => {
	emitter.emit('openpopup', IsAchievement.value)
}
const ScreenUnList = async (v) => {
	try {
		// 构建参数对象，合并筛选条件
		const params = {
			businessId: uni.getStorageSync('businessId'),
			isAllot: 0,
			pageNumber: UnallocatedPageNumber.value + 1,
			pageSize: 10,
			productId: v.busProId,
			college: v.school,
			classTime: v.year,
			beginTime: v.startTime,
			endTime: v.endTime,
			addPeople: v.userId,
			name: searchValue.value,
			phoneFirst: searchValue.value.leng == 11 ? searchValue.value : '',
			isReturns: v.isReturn === '是' ? 1 : 2,
			...v
		};
		if (v.isReturn === '是') {
			params.isReturns = 1
		} else if (v.isReturn === '否') {
			params.isReturns = 2
		} else {
			params.isReturns = ''
		}
		let res = await getOrderList(params)
		console.log(res)
		unallocatedList.value = res.data.records || [];
	} catch (e) {

	}
}
const ScreenList = async (v) => {
	console.log(v, '已分配')
	try {
		// 构建参数对象，合并筛选条件
		const params = {
			businessId: uni.getStorageSync('businessId'),
			isAllot: 1,
			pageNumber: AllocatedPageNumber.value + 1,
			pageSize: 10,
			productId: v.busProId,
			college: v.school,
			classTime: v.year,
			beginTime: v.startTime,
			endTime: v.endTime,
			addPeople: v.userId,
			name: searchValue.value,
			phoneFirst: searchValue.value.leng == 11 ? searchValue.value : '',

			...v
		};
		//isReturns: v.isReturn === '是' ? 1 : 2,
		if (v.isReturn === '是') {
			params.isReturns = 1
		} else if (v.isReturn === '否') {
			params.isReturns = 2
		} else {
			params.isReturns = ''
		}

		console.log(params, 'params')
		let res = await getOrderList(params)
		allocatedTotal.value = res.data.total || 0;
		await allocatedListHandle(res.data.records)
	} catch (e) {

	}
}
emitter.on('UpdateData', (val) => {
	console.log(val, '筛选条件更新');
	// 保存当前筛选条件
	currentFilterParams.value = val;
	if (IsAchievement.value == '未分配订单') {
		ScreenUnList(val)
	} else {
		ScreenList(val)
	}
})
import { onShow } from '@dcloudio/uni-app';
getOrderListHandle()


</script>

<style lang="scss">
.scroll-Y {
	margin-top: -10rpx;
	box-sizing: border-box;
	/* 原有底部内边距 */
}

-page {
	padding: 0;
	flex: 1;
	background-color: $u-bg-color;

	&__item {

		&__title {
			color: $u-tips-color;
			background-color: $u-bg-color;
			padding: 15px;
			font-size: 15px;

			&__slot-title {
				color: $u-primary;
				font-size: 14px;
			}
		}
	}
}

.u-nav-slot {
	@include flex;
	align-items: center;
	justify-content: space-between;
	border-width: 0.5px;
	border-radius: 100px;
	border-color: $u-border-color;
	padding: 3px 7px;
	opacity: 0.8;
}

.u-tabs__wrapper__nav {
	border-bottom: 1px solid rgba(239, 239, 239, 1);
}

.search_box {
	display: flex;
	width: 100%;
	background-color: #fff;
	align-items: center;
	padding-left: 42rpx;
	padding-right: 32rpx;
	box-sizing: border-box;
	padding-top: 20rpx;
	padding-bottom: 20rpx;
	border-bottom: 1px solid rgba(239, 239, 239, 1);
	// border-top: 1px solid rgba(239, 239, 239, 1);
	;
}

.search_input {
	width: 90%;
	height: 44px;
	line-height: 22px;
	border-radius: 22px;
	background-color: rgba(255, 255, 255, 1);
	color: rgba(51, 51, 51, 1);
	font-size: 16px;
	text-align: left;
	padding-left: 20px;
	font-family: -regular;
	border: 1px solid rgba(204, 204, 204, 1);
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search_r {
	margin-left: 20rpx;
	display: flex;
	align-items: center;

	.text-r {
		line-height: 40rpx;
		color: rgba(154, 154, 154, 1);
		font-size: 28rpx;
		text-align: left;
		margin-left: 10rpx;
		font-family: PingFangSC-regular;
	}
}

.del_box {
	width: 100%;
	height: 56px;
	line-height: 22px;
	background-color: rgba(255, 255, 255, 1);
	color: rgba(0, 0, 0, 1);
	font-size: 15px;
	text-align: center;
	box-shadow: 0px -2px 6px 0px rgba(239, 239, 239, 0.4);
	font-family: -regular;
	position: fixed;
	bottom: 0;
	display: flex;
	justify-content: space-between;
	align-items: center;
	z-index: 20;
	/* 提高z-index确保在分页条上方 */
}

/* 修改右侧图标颜色 */
.noData {
	width: 50%;
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
}



.littleArr {
	position: absolute;
	width: 100%;
	bottom: 0;
}
</style>
